import { createUseStyles } from "react-jss";
import { isUndefined } from "@ct0/functions";
import Input from "../../components/Input";
import React, { useEffect, useState } from "react";
import type { FieldBaseType } from "../../type";

const useStyles = createUseStyles({
  input: {
    "& > input": {
      width: "50px",
    },
  },
});

export default function NumberWithUnit({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<{ value?: number; unit?: string }>;
  isValid: boolean;
  onChange: (value: { value?: number; unit?: string } | null) => void;
}) {
  const classes = useStyles();
  const {
    value: propsValue,
    defaultValue,
    placeholder,
    prefix,
    suffix,
    meta,
    disabled,
    options,
  } = field;

  const value = propsValue ??
    defaultValue ?? { value: undefined, unit: undefined };

  const handler = (v?: string, u?: string) => {
    const V = isUndefined(v)
      ? value.value
      : v === ""
      ? undefined
      : parseFloat(v);
    const U = isUndefined(u) ? value.unit : u;
    onChange({ value: V, unit: U });
  };

  const [units, setUnits] = useState<Array<{ label: string; value: string }>>(
    []
  );

  useEffect(() => {
    if (typeof options == "undefined") return;
    const mapOptions = (
      opts: Array<{
        value: string | number;
        label: string;
      }>
    ) => opts.map((i) => ({ label: i.label, value: String(i.value) }));
    if (typeof options == "function") {
      options().then((r) => setUnits(mapOptions(r)));
    } else {
      setUnits(mapOptions(options));
    }
  }, [options]);

  return (
    <Input
      placeholder={placeholder}
      className={classes.input}
      invalid={!isValid}
      disabled={disabled}
      value={isUndefined(value.value) ? "" : String(value.value)}
      type="number"
      min={meta?.min}
      max={meta?.max}
      prefix={prefix}
      suffix={suffix}
      unitValue={value.unit}
      units={units}
      onUnitChange={(v) => handler(undefined, v)}
      onChange={(v) => handler(v)}
    />
  );
}
